package com.wjjun.app

import android.app.Application
import android.util.Log
import com.google.auto.service.AutoService
import com.tencent.matrix.Matrix
import com.tencent.matrix.batterycanary.BatteryMonitorPlugin
import com.tencent.matrix.batterycanary.monitor.BatteryMonitorCallback.BatteryPrinter
import com.tencent.matrix.batterycanary.monitor.BatteryMonitorConfig
import com.tencent.matrix.batterycanary.monitor.feature.JiffiesMonitorFeature
import com.tencent.matrix.iocanary.IOCanaryPlugin
import com.tencent.matrix.iocanary.config.IOConfig
import com.tencent.matrix.resource.ResourcePlugin
import com.tencent.matrix.resource.config.ResourceConfig
import com.tencent.matrix.trace.TracePlugin
import com.tencent.matrix.trace.config.TraceConfig
import com.wjjun.app.matrix.MatrixConfig
import com.wjjun.app.matrix.MatrixListener
import com.wjjun.base.utils.ModuleInitHandler


@AutoService(ModuleInitHandler::class)
class InitHandler : ModuleInitHandler{

    override fun onInit(app: Application) {
        Log.e("主模块开始初始化",System.currentTimeMillis().toString());
        //使用腾讯的matrix框架进行监控
        val builder = Matrix.Builder(app)
        builder.pluginListener(MatrixListener(app))
        val config = MatrixConfig()

        //trace, 卡顿监测
        val traceConfig = TraceConfig.Builder()
            .dynamicConfig(config) //按照自己需求开启以下监控任务
            .enableFPS(false)
            .enableEvilMethodTrace(true)
            .enableAnrTrace(true)
            .enableStartup(true) //一定要写，改成自己项目中的splash页面即可，不然会奔溃
            .splashActivities("sample.tencent.matrix.SplashActivity;") //debug模式
            .isDebug(true) //dev环境
            .isDevEnv(false)
            .build()
        val tracePlugin = TracePlugin(traceConfig)
        builder.plugin(tracePlugin)

        //resource,资源泄露监测
        val resourceConfig: ResourceConfig = ResourceConfig.Builder()
            .dynamicConfig(config) //true获取hprof文件，否则没法分析哪里内存泄露了
            .setDetectDebuger(false)
            .build()

        val resourcePlugin = ResourcePlugin(resourceConfig)
        builder.plugin(resourcePlugin)
        //当activity destroy之后，自动断开从引用的view到gc root之间的路径
        ResourcePlugin.activityLeakFixer(app)

        //IO,文件等io监测
        val ioPlugin = IOCanaryPlugin(IOConfig.Builder()
            .dynamicConfig(config).build())
        builder.plugin(ioPlugin)

        //电源监测
        val batteryPlugin = BatteryMonitorPlugin(
            BatteryMonitorConfig.Builder()
            .enable(JiffiesMonitorFeature::class.java)
            .enableStatPidProc(true)
            .greyJiffiesTime(30 * 1000L)
            .setCallback(BatteryPrinter())
            .build())
        builder.plugin(batteryPlugin)

        Matrix.init(builder.build())

        //启动插件
        tracePlugin.start()
        resourcePlugin.start()
        ioPlugin.start()
        batteryPlugin.start()

        Log.e("主模块完成初始化", System.currentTimeMillis().toString());
    }
}